package com.tutu.common.dwr.manager;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.impl.DefaultScriptSession;
import org.directwebremoting.impl.DefaultScriptSessionManager;

import com.tutu.common.GlobalConstants;
import com.tutu.user.entity.SysUser;

public class DwrScriptSessionManager extends DefaultScriptSessionManager {
	/**
	 * 存放在SESSION中ScriptSessionId 标识
	 */
	public static final String SESSION_DWR_SCRIPTSESSION_ID="SESSION_DWR_SCRIPTSESSION_ID";
	
	public DwrScriptSessionManager(){
		addScriptSessionListener(new ScriptSessionListener() {
			
			@Override
			public void sessionDestroyed(ScriptSessionEvent event) {
			}
			
			@Override
			public void sessionCreated(ScriptSessionEvent event) {
//				获得新创建的scriptSession
				ScriptSession scriptSession = event.getSession();
				WebContext webContext = WebContextFactory.get();
				HttpServletRequest request = webContext.getHttpServletRequest();
				SysUser currentUser = GlobalConstants.getCurrentUser();
				if(null == currentUser){
//					销毁这个scriptsession
					scriptSession.invalidate();
					request.getSession().invalidate();
					return;
				}
				String scriptSessionId = (String) request.getSession().getAttribute(SESSION_DWR_SCRIPTSESSION_ID);
				if(StringUtils.isNotEmpty(scriptSessionId)){
//					注销旧的scriptSession
					DefaultScriptSession defaultScriptSession = sessionMap.get(scriptSessionId);
					if(null != defaultScriptSession){
						invalidate(defaultScriptSession);
					}
				}
				request.getSession().setAttribute(SESSION_DWR_SCRIPTSESSION_ID, scriptSession.getId());
				scriptSession.setAttribute(GlobalConstants.SESSION_USER_INFO, currentUser.getUserId());
			}
		});
	}
}
